import java.io.*;
import java.net.Inet4Address;
import java.net.InetSocketAddress;
import java.net.Socket;

public class Client {

    public static void main(String[] args) throws Exception {
        Socket socket = new Socket();

        //设置socket超时时间
        socket.setSoTimeout(3000);

        //连接本地端口2000 超时3000ms
        socket.connect(new InetSocketAddress(Inet4Address.getLocalHost(),2000),3000);
        System.out.println("已发起服务器连接，并进入后续流程～");
        System.out.println("客户端信息：" + socket.getLocalAddress() + " P:" + socket.getLocalPort());
        System.out.println("服务器信息：" + socket.getInetAddress() + " P:" + socket.getPort());
        try {
            //TODO 发送接收数据
            todo(socket);
        }catch (Exception e){
            System.out.println("异常关闭");
        }
    }

    /**
     * 发送接收数据方法
     * @param socket
     */
    private static void todo(Socket socket) throws Exception {
        //键盘输入流
        InputStream in = System.in;
        BufferedReader input =new BufferedReader(new InputStreamReader(in));

        //得到socket输出流，并转换为打印流
        OutputStream outputStream = socket.getOutputStream();
        PrintStream socketPrintStream = new PrintStream(outputStream);

        // 得到Socket输入流，并转换为BufferedReader
        InputStream inputStream = socket.getInputStream();
        BufferedReader socketBufferedReader =new BufferedReader(new InputStreamReader(inputStream));

        boolean flag = true;

        do {
            //读取键盘输入一行
            String inData = input.readLine();
            //发送到服务器
            socketPrintStream.println(inData);

            //从服务读取一行
            String echo = socketBufferedReader.readLine();
            if("bye".equalsIgnoreCase(echo)){
                flag = false;
            }else{
                System.out.println(echo);
            }

        }while (flag);

        //资源释放
        socketPrintStream.close();
        socketBufferedReader.close();
    }
}
